<?php


namespace app\cms\community\thirdPartyApi\payPal;


use app\cms\community\thirdPartyApi\payPal\lib\publicParams;
use iflow\Response;
use PayPalCheckoutSdk\Core\PayPalHttpClient;
use PayPalCheckoutSdk\Core\ProductionEnvironment;
use PayPalCheckoutSdk\Core\SandboxEnvironment;
use PayPalCheckoutSdk\Orders\OrdersCaptureRequest;
use PayPalCheckoutSdk\Orders\OrdersCreateRequest;
use PayPalHttp\HttpException;
use PayPalHttp\HttpResponse;

class pay extends \app\cms\community\thirdPartyApi\abstracts\Pay
{

    protected array $type = [
        'jsapi' => 'JsApiPay',
        'native' => 'QrApiPay',
        'h5' => 'H5ApiPay'
    ];

    public HttpResponse $response;

    protected array $config;

    protected ProductionEnvironment|SandboxEnvironment $environment;
    protected PayPalHttpClient $client;
    protected object $request;

    public function __construct(protected publicParams $publicParams)
    {
        $this->config = $this->publicParams -> getConfig();
    }

    public function createOrder(string $type): bool|Response {
        // TODO: Implement createOrder() method.

        $type = strtolower($type);
        if (empty($this->type[$type])) return message() -> nodata('请选择正确的支付类型');

        // 验证是否为沙箱模式
        $environmentClass = ProductionEnvironment::class;
        if ($this->publicParams -> sandbox) {
            $environmentClass = SandboxEnvironment::class;
        }

        // 执行请求操作
        $this->environment = new $environmentClass($this->config['appid'], $this->config['appsecret']);
        $this->client = new PayPalHttpClient($this->environment);

        return call_user_func([$this, $this->type[$type]]);
    }

    /**
     * capture 订单回调方法
     * @return Response
     * @throws \PayPalHttp\IOException
     */
    public function JsApiPay(): Response
    {
        // TODO: Implement JsApiPay() method.
        $this->request = new OrdersCaptureRequest($this->publicParams -> orderID);
        $this->request->prefer('return=representation');
        try {
            $response = $this->client->execute($this->request);
            return message() -> success('订单处理成功', $response -> result);
        }catch (HttpException $exception) {
            return message() -> update_failed("订单处理错误，请稍后重试");
        }
    }

    public function QrApiPay(): Response
    {
        // TODO: Implement QrApiPay() method.
        return message() -> nodata("暂不支持的支付功能");
    }

    /**
     * 创建订单信息
     * @return Response
     * @throws \PayPalHttp\IOException
     */
    public function H5ApiPay(): Response
    {
        // TODO: Implement H5ApiPay() method.

        try {
            $this->request = new OrdersCreateRequest();
            $this->request->prefer('return=representation');
            $this->request->body = [
                "intent" => $this->publicParams -> intent,
                "purchase_units" => [[
                    "reference_id" => $this->publicParams -> referenceId,
                    "amount" => $this->publicParams -> amount
                ]],
                // 支付回调
                "application_context" => [
                    "cancel_url" => $this->config['cancel_url'], // 取消
                    "return_url" => $this->config['return_url']  // 执行
                ]
            ];
            $this->response = $this->client->execute($this->request);
            $this->result = $this->response -> result;
            return message() -> success('创建订单成功', $this->result);
        } catch (HttpException) {
            return message() -> update_failed("创建订单失败请重试");
        }
    }
}